package com.finger.wx.assistant;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.finger.wx.assistant.service.WeiXinServiceImpl;
import com.finger.wx.assistant.service.WeiXinSevice;
import com.finger.wx.assistant.util.HttpRequest;
import com.finger.wx.assistant.util.KLog;
import com.finger.wx.assistant.util.ToolString;
import com.finger.wx.assistant.vo.Constant;
import com.finger.wx.assistant.vo.InitParam;

@SuppressLint("NewApi")
public class TaskService extends Service {

	protected String TAG = "TaskService";
	public boolean threadFlag = true;
	MyThread mThread;

	private String mac;
	private Context context;

	private WeiXinSevice wxService = new WeiXinServiceImpl();

	@Override
	public IBinder onBind(Intent arg0) {
		KLog.i(TAG, "onBind()");
		return null;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		KLog.i(TAG, "onUnbind()");
		return false;
	}

	@Override
	public void onCreate() {
		KLog.i(TAG, "onCreate()");
		mac = getMAC();
		context = TaskService.this;
		super.onCreate();
	}

	/* Called when Activity startService */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		KLog.i(TAG, "onStartCommand()");
		myStartService();
		return super.onStartCommand(intent, flags, startId);
	}

	/* Called by onStartCommand, initialize and start runtime thread */
	private void myStartService() {
		threadFlag = true;
		mThread = new MyThread();
		mThread.start();
	}

	/* Service stop after thread close */
	public void myStopService() {
		threadFlag = false;
		stopSelf();
	}

	@Override
	public void onDestroy() {
		KLog.i(TAG, "onDestroy()");
		super.onDestroy();

		threadFlag = false;
		boolean retry = true;
		while (retry) {
			try {
				retry = false;
				mThread.join();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * Thread runtime
	 */
	public class MyThread extends Thread {
		String acid;
		String isi;
		String ic;

		@Override
		public void run() {
			super.run();
			// TODO runtime
			while (threadFlag) {
				KLog.i(TAG, "Thread pulse,mac:" + mac);
				try {

					if (ToolString.isNoBlankAndNoNull(mac)) {
						// 1.获取任务
						String task = query(mac);
						KLog.i(TAG, "query task:" + task);

						if (ToolString.isNoBlankAndNoNull(task)) {
							KLog.i(TAG, "Thread pulse,task:" + task);
							JSONObject json = JSON.parseObject(task);
							String result = json.getString("result");
							if ("1".equals(result)) {
								JSONObject data = json.getJSONObject("data");
								isi = data.getString("instruct_set_id");
								acid = data.getString("account_id");
								JSONObject instruct_info = data.getJSONObject("instruct_info");
								ic = instruct_info.getString("code");

								// 2.执行 0 执行失败，1成功
								int status = execute(instruct_info);
								KLog.i(TAG, "execute status:" + status);

								int tfs = getTotalFriends();
								// 3.反馈
								String feedRet = feedback(mac, acid, isi, ic, status, tfs);
								KLog.i(TAG, "feedback,result:" + feedRet);
							}
						}

						sleep(2000);
					} else {
						KLog.i(TAG, "Thread pulse,current task is null");
						sleep(10000);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取设备mac
	 * 
	 * @return mac中的字母都是大写
	 */
	public String getMAC() {
		String macAddress = "";
		if (macAddress == null || "".equals(macAddress.trim())) {
			try {
				WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
				WifiInfo wifiInfo = wifi.getConnectionInfo();
				macAddress = wifiInfo.getMacAddress();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (macAddress != null && macAddress.length() > 0) {
				macAddress = macAddress.toUpperCase();
			}
		}
		return macAddress;
	}

	/***
	 * 查询好友数量
	 * 
	 * @return
	 */
	public int getTotalFriends() {
		return 0;
	}

	/**
	 * 获取任务
	 * 
	 * @param mac2
	 */
	public String query(String t_mac) {
		StringBuilder sb = new StringBuilder();
		sb.append(Constant.queryUrl).append("?mac=").append(t_mac);
		return HttpRequest.get(sb.toString()).body("utf-8");
	}

	/**
	 * 执行任务
	 * 
	 * @param task
	 * @return
	 */
	public int execute(JSONObject j) {
		KLog.i(TAG, "execute,json:" + j.toJSONString());
		int result = 0;
		String code = j.getString("code");
		JSONObject reqData = new JSONObject();
		try {
			reqData = j.getJSONObject("data");
			
			if ("IAL".equals(code)) {// 微信登录
				// 修改定位信息
				InitParam param = new InitParam();
				param.setLat(reqData.getString("lat"));
				param.setLon(reqData.getString("lon"));
				param.setLac(reqData.getString("lac"));
				param.setCid(reqData.getString("cid"));
				param.setMnc(reqData.getString("mnc"));
				wxService.init(param);

				Thread.sleep(3000);
				result = wxService.login(reqData.getString("account"), reqData.getString("pwd")) ? 1 : 0;
			} else if ("IPN".equals(code)) {// 加附近的的人
				result = wxService.sayHiNearByFriend(0, reqData.getIntValue("max_additions"), reqData.getString("say_hi_text")) ? 1
						: 0;
			} else if ("IML".equals(code)) {// 点赞
				result = wxService.momentsLike(reqData.getIntValue("max_additions")) ? 1 : 0;
			} else if ("ISM".equals(code)) {// 发朋友圈
				result = wxService.shareMoments(reqData.getString("content"), false) ? 1 : 0;
			} else if ("IALO".equals(code)) {// 微信退出
				result = wxService.logout() ? 1 : 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = 0;
		}
		KLog.i(TAG, "execute,result:" + result);
		return result;
	}

	/**
	 * 反馈结果
	 * 
	 * @param t_mac
	 * @param t_acid
	 *            微信账号
	 * @param t_isi
	 *            指令集ID
	 * @param t_ic
	 *            指令编码
	 * @param t_status
	 *            执行状态
	 * @param t_tsf
	 *            当前好友数量
	 * @return
	 */
	public String feedback(String t_mac, String t_acid, String t_isi, String t_ic, int t_status, int t_tsf) {
		StringBuilder sb = new StringBuilder();
		sb.append(Constant.feedBack).append("?mac=").append(t_mac)// mac地址
				.append("&acid=").append(t_acid)// 账号id
				.append("&isi=").append(t_isi)// 指令集id
				.append("&ic=").append(t_ic)// 指令编码
				.append("&status=").append(t_status)// 指令执行状态
				.append("&tfs=").append(t_tsf);// 当前好友数

		return HttpRequest.get(sb.toString()).body("utf-8");
	}

}
